package com.baitiaojun.video.handler;

import com.alibaba.fastjson.JSONObject;
import com.baitiaojun.api.domain.video.VideoComment;
import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.video.config.properties.CommentsMQProperties;
import com.baitiaojun.video.support.RedisSupport;
import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @类名 RabbitMQHandler
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/3/7 16:28
 * @版本 1.0
 */
@Slf4j
@Component
public class RabbitMQHandler {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private CommentsMQProperties commentsMQProperties;

    @Autowired
    private RedisSupport redisSupport;

    @Retryable
    @Async
    public void send(VideoComment videoComment) {
        log.info("发送消息");
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(String.valueOf(videoComment.getId()));
        Message message = MessageBuilder.withBody(JSONObject.toJSONString(videoComment).getBytes(StandardCharsets.UTF_8)).build();
        message.getMessageProperties().setCorrelationId(correlationData.getId());
        rabbitTemplate.convertAndSend(commentsMQProperties.getExchange(), commentsMQProperties.getRoutingKey(), message, correlationData);
    }

    @RabbitListener(queues = "mirror_comments_queue")
    public void consume(Message message) {
        log.info("消费消息");
        MessageProperties messageProperties = message.getMessageProperties();
        VideoComment videoComment = JSONObject.parseObject(new String(message.getBody()), VideoComment.class);
        redisSupport.setValue(ConstantUtil.COMMENT_APPEND_KEY + messageProperties.getCorrelationId(), videoComment, 1, TimeUnit.DAYS);
    }
}
